package org.lgq.autoconfigure;


import org.apache.shardingsphere.elasticjob.reg.base.CoordinatorRegistryCenter;
import org.apache.shardingsphere.elasticjob.reg.zookeeper.ZookeeperConfiguration;
import org.apache.shardingsphere.elasticjob.reg.zookeeper.ZookeeperRegistryCenter;
import org.lgq.parser.ElasticJobCfgParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p>Conditional 加载条件，默认是直接加载</p>
 * <p>ConditionalOnProperty 有相关配置才装载 es-job 强依赖zk的 matchIfMissing 没有就不加载</p>
 * <p>EnableElasticJob 注解，导入JobParserAutoConfiguration此类，如果满足Conditional，则继续走下去</p>
 *
 * @author DevLGQ
 * @version 1.0
 */
@Configuration
@ConditionalOnProperty(prefix = "elastic.job.zk", name = {"namespace", "serverLists"}, matchIfMissing = false)
@EnableConfigurationProperties(JobZookeeperProperties.class)
public class JobParserAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(JobParserAutoConfiguration.class);

    /**
     * zookeeper注册中心
     *
     * @param jobZookeeperProperties
     * @return
     */
    @Bean(initMethod = "init")
    public CoordinatorRegistryCenter zookeeperRegistryCenter(JobZookeeperProperties jobZookeeperProperties) {
        ZookeeperConfiguration zkConfig = new ZookeeperConfiguration(jobZookeeperProperties.getServerLists(),
                jobZookeeperProperties.getNameSpace());
        zkConfig.setDigest(jobZookeeperProperties.getDigest());
        zkConfig.setMaxRetries(jobZookeeperProperties.getMaxRetries());
        zkConfig.setBaseSleepTimeMilliseconds(jobZookeeperProperties.getBaseSleepTimeMilliseconds());
        zkConfig.setMaxSleepTimeMilliseconds(jobZookeeperProperties.getMaxSleepTimeMilliseconds());
        zkConfig.setConnectionTimeoutMilliseconds(jobZookeeperProperties.getConnectionTimeoutMilliseconds());
        zkConfig.setSessionTimeoutMilliseconds(jobZookeeperProperties.getSessionTimeoutMilliseconds());
        log.info("初始化job注册中心成功, zkaddress: {} namespace: {}", jobZookeeperProperties.getServerLists(),
                jobZookeeperProperties.getNameSpace());
        return new ZookeeperRegistryCenter(zkConfig);
    }

    @Bean
    public ElasticJobCfgParser elasticJobCfgParser(CoordinatorRegistryCenter zookeeperRegistryCenter) {
        return new ElasticJobCfgParser(zookeeperRegistryCenter);
    }

}
